package com.luo.d3s.ext.event.jdbc.publish;

import com.luo.d3s.core.domain.event.DomainEvent;
import com.luo.d3s.core.domain.event.DomainEventPublisher;
import com.luo.d3s.core.domain.event.DomainEventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 领域事件发布器 - 分发器
 *
 * @author luohq
 * @date 2023-02-25 10:10
 */
@Component
public class DomainEventPublisherDispatcher {

    private static final Logger log = LoggerFactory.getLogger(DomainEventPublisherDispatcher.class);


    @Resource
    private  List<DomainEventPublisher> domainEventPublisherList;

    /**
     * 根据类型调用不同的发送器发送事件
     *
     * @param domainEvent 领域事件
     */
    public void publishByType(DomainEvent domainEvent) {
        if (null == domainEvent.getTypes() || 0 == domainEvent.getTypes().length) {
            log.error("Publish event type is null: {}", domainEvent);
            return;
        }

        //遍历当前事件的发送类型
        for (DomainEventType type : domainEvent.getTypes()) {
            //根据类型调用不同的发送器发送事件
            this.domainEventPublisherList.stream()
                    .filter(domainEventPublisher -> type.equals(domainEventPublisher.type()))
                    .forEach(domainEventPublisher -> domainEventPublisher.publish(domainEvent));
        }
    }

}
